package com.huaji.eat;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try{
            File file = new File("data/data/com.huaji.eat/data.bin");
            Data.foods = new ArrayList<>();
            if (!file.exists()) {
                file.createNewFile();
            } else {
                FileInputStream stream = new FileInputStream(file);
                ObjectInputStream object = new ObjectInputStream(stream);
                Data.foods =  (List<String>) object.readObject();
                stream.close();
                object.close();
            }
        } catch (FileNotFoundException e) {
            Toast.makeText(MainActivity.this, "未找到数据文件", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } catch (IOException e) {
            Toast.makeText(MainActivity.this, "IO异常", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            Toast.makeText(MainActivity.this, "类异常", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }

        Button btn_food_mana = findViewById(R.id.btn_food_mana);
        btn_food_mana.setOnClickListener(v -> startActivity(new Intent().setClass(MainActivity.this, FoodManaActivity.class)));

        Button btn_eat = findViewById(R.id.btn_eat);
        btn_eat.setOnClickListener(v -> {
            TextView txt_food = findViewById(R.id.txt_food);
            Random random = new Random();
            int rint = random.nextInt(Data.foods.size());

            txt_food.setText(Data.foods.get(rint));
        });
    }

    @Override
    protected void onPause() {
        super.onPause();

        try {
            FileOutputStream stream = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Data.bin");
            ObjectOutputStream object = new ObjectOutputStream(stream);
            object.writeObject(Data.foods);
            stream.close();
            object.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}